<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>体验websocket</title>
    <style>
      #contanier {
        width: 500px;
        height: 400px;
        border: 2px dashed #7575e7;
        overflow-y: auto;
      }
    </style>
  </head>

  <body>
    <div id="contanier"></div>
    <!-- 1  建立连接 (拨号) -->
    <!-- 2  发消息 接消息 -->
    <!-- 3  关闭连接 -->
    <input type="text" id="message" />
    <button id="btn1">建立连接</button>
    <button id="btn2">发送消息</button>
    <button id="btn3">关闭连接</button>

    <script>
      var dom = document.getElementById('contanier')
      var inputDom = document.getElementById('message')
      var btn1 = document.getElementById('btn1')
      var btn2 = document.getElementById('btn2')
      var btn3 = document.getElementById('btn3')
      let ws
      btn1.onclick = function () {
        // 建立连接
        ws = new WebSocket('ws://121.40.165.18:8800')
        console.log(ws)
        ws.onopen = function () {
          dom.innerHTML += `<p>与服务器成功建立连接</p>`
        }
        // 响应消息会触发message事件
        ws.onmessage = function (e) {
          dom.innerHTML += `<p>服务器说${e.data}</p>`
        }
        //断开链接会触发close事件
        ws.onclose = function () {
          console.log('断开了链接')
          dom.innerHTML += `与服务器断开链接</p>`
        }
        // 断开连接
        ws.onerror = function () {
          console.log('链接失败')
        }
      }
      btn2.onclick = function () {
        if (inputDom.value.length === 0) {
          return
        }
        //发送消息
        ws.send(inputDom.value)
        dom.innerHTML =
          dom.innerHTML + `<p style='color: red'>我说:${inputDom.value}</p>`
        inputDom.value = ''
      }

      // 关闭连接
      btn3.onclick = function () {
        ws.close() // 关闭连接
      }
    </script>
  </body>
</html>
